//
//  LoginVC.m
//  DataStatistics
//
//  Created by Kang on 15/12/24.
//  Copyright © 2015年 YTYangK. All rights reserved.
//

#import "LoginVC.h"
#import "LoginViewModel.h"
#import "UITextField+LolitaText.h"
#import <CommonCrypto/CommonDigest.h>


 //秘籍
//#import "CheatsClasses.h"
//#import "CheatsClassesFlowLayout.h"

@interface LoginVC ()<UITextFieldDelegate,UITextViewDelegate>
{
    /** 初始化位置*/
    CGRect frameDefault;
    /** 判断是否点击了 */
    BOOL   isClick;
}

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *TitleLayout;
@property (weak, nonatomic) IBOutlet UILabel *TitleLabel;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *W_keepPassword;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *H_login;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *W_login;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Y_login;
// 密码输入框
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Y_pas;
// 账号输入框
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *Y_ame;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Y_acount;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Y_forget;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *backgroundBottom;

@end

@implementation LoginVC

//singleton_for_implementation(LoginVC)

- (void)viewDidLoad {
    [super viewDidLoad];
    self.password.delegate              = self;
    self.phoneNum.delegate              = self;
    [self updateUI];
    [self TLayout];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}


#pragma mark - 更新UI
- (void)updateUI {
    frameDefault = self.view.frame;
    
    //if (SCREEN_WIDTH == 320) {
        self.reclsTeredBtn.titleLabel.font = self.forcetPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        self.phoneNum.font  = self.password.font = [UIFont systemFontOfSize:20];
   // }
    
    
    [UITextField addYTYanKTextFielStyle1:self.phoneNum withString:NSLocalizedString(@"account",@"用户名")];
    [self.phoneNum addTarget:self action:@selector(LVCtextLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    
    self.password.secureTextEntry       =  YES; //密码类型
    self.password.returnKeyType         = UIReturnKeyDone;
    [UITextField addYTYanKTextFielStyle1:self.password withString:NSLocalizedString(@"password",@"密码")];
    
    [self.password addTarget:self action:@selector(LVCtextLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    
    [self rememberAction];
    
}

// 判断是否禁止使用
- (void)LVCtextLengthMethod:(UITextField *)textField {
    
    
    if (self.password.text.length >0 && self.phoneNum.text.length>0) {
        _password.enablesReturnKeyAutomatically  = NO;
        _loginBtn.userInteractionEnabled   = YES;
        [_loginBtn setBackgroundColor:RGB(254, 208, 48, 1.0)];
        
         }else {
        _password.enablesReturnKeyAutomatically  = YES;
        _loginBtn.userInteractionEnabled = NO;
             [_loginBtn setBackgroundColor:[UIColor grayColor]];
         
         }
    
    if(textField.tag == 1 ){
        if (textField == _phoneNum) {
            if (textField.text.length > 15) {
                textField.text = [textField.text substringToIndex:15];
            }
        }
    }else {
        if (textField == _password) {
            if (textField.text.length > 12) {
                textField.text = [textField.text substringToIndex:12];
            }
        }
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

//输入框清空后调用的方法
-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    NSString *str = self.password.text;
    NSString *str1 = self.phoneNum.text;
    if (str.length >0 && str1.length>0) {
        _password.enablesReturnKeyAutomatically  = YES;
        _loginBtn.userInteractionEnabled = NO;
        [_loginBtn setBackgroundColor:[UIColor grayColor]];
        
    }
    
    return YES;//textField.text;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _phoneNum) {
    [self.password becomeFirstResponder];
        [_password x];
        
    }else {
         [self loginBtnCiake:_loginBtn];
    }
    return  YES;
}


// 判断登录前操作是否合法
- (NSString *)checkUserDetails {
    NSCharacterSet *whiteNewChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *userName = [_phoneNum.text stringByTrimmingCharactersInSet:whiteNewChars];
    NSString *password = [_password.text stringByTrimmingCharactersInSet:whiteNewChars];
    NSString *message = @"";
    
    if ([userName length] == 0 || [password length] == 0) {
        if ([userName isEqualToString:@"000000"] && [password isEqualToString:@""]) {
            self.phoneNum.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            self.phoneNum.text = @"";
            self.password.text = @"";
             [self resignRespondersForTextFields];
        }
        message = [NSString stringWithFormat:NSLocalizedString(@"LvcTip_0", @"账号或密码不能为空")];
    }else {
        if ([self.phoneNum.text rangeOfString:@" "].location != NSNotFound) {
            message = [NSString stringWithFormat:NSLocalizedString(@"LvcTip_7",@"用户名不能包含有空格")];
        }else {
            if ([password length] < 6) {
                message  = [NSString stringWithFormat:NSLocalizedString(@"LvcTip_8",@"密码长度要6~12位的长度。")];
            }
        }
    }
    return message;
}


// 动画
- (BOOL)resignRespondersForTextFields {
    if (isClick) {
        isClick = NO;
        if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0") ){
            [UIView animateWithDuration:0.24 animations:^{
                [self.view setFrame:frameDefault];
            } completion:nil];
        }
        
        [_phoneNum resignFirstResponder];
        [_password resignFirstResponder];
    }
    return isClick;
}


/** 键盘显示  */
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (!isClick) {
        isClick = YES;
    }
    if (_phoneNum.isFirstResponder == true || _password.isFirstResponder == true) {
         CGRect newFrome = self.view.frame;
        if (SCREEN_HEIGHT == 480 ) {
            newFrome.origin.y = -2 * textField.frame.size.height - 40;
        } else if (SCREEN_HEIGHT == 568) {
            if (textField == _password) {
                newFrome.origin.y =   (-1 * textField.frame.size.height - 20) -0.5;
            }else {
                newFrome.origin.y =   -1 * textField.frame.size.height - 20;
            }
        }
        [UIView animateWithDuration:0.24 animations:^{
            [self.view setFrame:newFrome];
        } completion:^(BOOL finished) { }];
    }
}

/** 键盘隐藏 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self resignRespondersForTextFields];
}


/** singUp Or Forgot 按钮跳转设置 */
- (void)ChoiceBoxAction:(UIButton *)btn {
     BOOL  isRe = [self resignRespondersForTextFields];
    
    UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] init];
    backIetm.title = NSLocalizedString(@"back", nil);
    self.navigationItem.backBarButtonItem = backIetm;
    
    if (isRe == NO) {
        if (btn.tag == 1004 ) {
            _signStr = @"Forget";
            [self performSegueWithIdentifier:@"pushRegister" sender:self];
            
        }
        if (btn.tag == 1003) {
            _signStr = @"Registered";
            [self performSegueWithIdentifier:@"pushRegister" sender:self];
            
        }
    }
}

 //跳转+ 记住密码
- (void)preservationInformation {
    
    [[NSUserDefaults standardUserDefaults] setObject:_phoneNum.text forKey:@"MDC_userCode"];
    
    [[NSUserDefaults standardUserDefaults] setObject:_password.text forKey:MDC_PASSWORD_VLUE];
    
    [LoginViewModel loginWithViewController:self];
}


/** 获取密码的方法*/
- (void)rememberAction {
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isAutomaticLogin"]isEqualToString:@"YES"]) {
        _phoneNum.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"MDC_userCode"];
        _password.text = [[NSUserDefaults standardUserDefaults]objectForKey:MDC_PASSWORD_VLUE];
        if ([_password.text isEqualToString:@""]) {
            self.loginBtn.userInteractionEnabled = NO;
        }
    }else {
        
        _phoneNum.text = @"";
        _password.text = @"";
    }
}


#pragma mark - 登陆请求
- (IBAction)loginBtnCiake:(UIButton *)sender {
    //admin 正式密码--in150601
    
    NSString *erorMessage = [self checkUserDetails];
    if (![erorMessage length]) {
        NSMutableString *mutNumStr = [self.phoneNum.text mutableCopy];
        NSMutableString *mutPasStr  = [self.password.text mutableCopy];
        

        
        if ([NSUD objectForKey:MDC_REGISTRATION_ID] == nil) {
            [NSUD setObject:@"异常登记ID" forKey:MDC_REGISTRATION_ID];
        }
        
        NSLog(@"RID = =========== %@",[NSUD objectForKey:MDC_REGISTRATION_ID]);
        
        NSDictionary *dic = @{@"loginName":[NSString stringWithFormat:@"%@",mutNumStr],@"password":[self stringToMD5:[NSString stringWithFormat:@"%@",mutPasStr]],@"noticeId":[NSUD objectForKey:MDC_REGISTRATION_ID]};
        
        
        [LoginViewModel requestWithUrlForLoginIn:self andParam:dic success:^(LoginModel *model) {
            
            
            [NSUD setObject:model.token forKey:@"token"];//保存令牌
            [NSUD setObject:model.balance forKey:@"money"];//保存个人金额
            [NSUD setObject:model.name forKey:@"UserName"];//保存姓名


                [self preservationInformation]; // 保存密码加跳转
                [self resignRespondersForTextFields];//收键盘
            
        } failure:^(NSString *error) {
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:self.view];
        }];

    }else {
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:erorMessage toView:self.view];
    }
}


#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier compare:@"pushRegister"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:_signStr forKey:@"RAVCsignStr"];
    }
}


#pragma mark - get /set 
- (UIButton *)loginBtn {
     [_loginBtn setTitle:NSLocalizedString(@"logIn", @"登录") forState:UIControlStateNormal];
    
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")){
        _loginBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18.f];
    }
    
    return _loginBtn;
}

/** 按钮设置 */
- (UIButton *)reclsTeredBtn {
    [_reclsTeredBtn setTitle:NSLocalizedString(@"signUp", @"注册") forState:UIControlStateNormal];
    [_reclsTeredBtn addTarget:self action:@selector(ChoiceBoxAction:) forControlEvents:UIControlEventTouchDown];
    return  _reclsTeredBtn;
}

- (UIButton *)forcetPasswordBtn {
    [_forcetPasswordBtn setTitle:NSLocalizedString(@"forgotPassword", @"忘记密码") forState:UIControlStateNormal];
    [_forcetPasswordBtn addTarget:self action:@selector(ChoiceBoxAction:) forControlEvents:UIControlEventTouchDown];
    return _forcetPasswordBtn;
}

- (NSLayoutConstraint *)Y_login {
    
    
    if (SCREEN_WIDTH == 414) {
        
    }else if (SCREEN_WIDTH == 375) {
        _Y_login.constant = 100;
    }else if (SCREEN_WIDTH == 320) {
        _Y_login.constant  = 60;
    }else  {
        _Y_login.constant  = 80;
    }
    return _Y_login;
}


- (NSString *)signStr {
   return  @"";
}


-(void)TLayout{
    
    if (SCREEN_WIDTH == 414) {
        self.TitleLayout.constant = 225;
    }else if (SCREEN_WIDTH == 375) {
        self.TitleLayout.constant = 200;
    }else  {
        self.TitleLayout.constant = 170;
        self.TitleLabel.font = [UIFont boldSystemFontOfSize:18];
    }
    
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"812.0")){
        
        self.backgroundBottom.constant  = -35;
        self.bgImage.image = [UIImage imageNamed:@"登录背景x"];
        
        
        self.Y_ame.constant =-4;
        self.Y_pas.constant =-20;
                
    }

    
}


-(NSString *)stringToMD5:(NSString *)str
{
    
    const char *fooData = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(fooData, (CC_LONG)strlen(fooData), result);
    
    NSMutableString *saveResult = [NSMutableString string];
    
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [saveResult appendFormat:@"%02x", result[i]];
    }
    
    return saveResult;
}


- (IBAction)queding:(id)sender {
    
    [self.view endEditing:YES];
    
    [NSUD setObject:[NSString stringWithFormat:@"http://%@",self.iptextview.text] forKey:@"haha"];

    
}


@end
